// pages/users/intention/index.js
const {
  fillingAdd,
  fillingEdit,
  fillingInfo,
  citySubjectList,
  hignSchool,
  addScore,
  getScore
} = require('../../../api/api')
Page({

  /**
   * 页面的初始数据
   */
  data: {

    isDisability: false,
    isSurgery: false,
    isColorBlindness: false,
    isColorWeakness: false,
    medicalHistory: "",
    pluses: "",
    specialty: "",
    target: "",
    updateBy: "",
    username: "",
    vision: "",
    weight: "",
    options: ['是', '否'],
    region: [],
    region2:[],
    subjectList: [{
      name: '语文',
      isPreferred: 1,
      enName: 'chinese'
    }, {
      name: '数学',
      isPreferred: 1,
      enName: 'match'

    }, {
      name: '英语',
      isPreferred: 1,
      enName: 'english'

    }, {
      name: '物理',
      isPreferred: 0,
      enName: 'physics'

    }, {
      name: '历史',
      isPreferred: 0,
      enName: 'history'

    }, {
      name: '化学',
      isPreferred: 0,
      enName: 'chemistry'
    }, {
      name: '地理',
      isPreferred: 0,
      enName: 'geography'

    }, {
      name: '生物',
      isPreferred: 0,
      enName: 'biology'

    }, {
      name: '政治',
      isPreferred: 0,
      enName: 'politics'
    }],
    schoolList: ['第一中学', '第二中学'],
    schoolIndex: 0,
    plusOptions: [{
      checked: false,
      title: '烈士子女'
    }, {
      checked: false,
      title: '华侨子女'
    }, {
      checked: false,
      title: '少数民族'
    }],

    roleOptions: ['学生', '家长', '其他'],
    roleIndex: 0,
    sexOptionsImages: ['https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/sex_boy.jpg',
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/sex_girl.jpg'
    ],
    sexIndex: 0,
    sexOptions: ['男', '女'],
    expand: true,
    subOptions: ['普通历史', '艺体类历史', '普通物理', '艺体类物理'],
    subIndex: 0,
    length: 3,
    pluses: '',
    graphy: '',
    roles: '学生',
    normalSubject: '',
    abnormalSubject: '',
    supernormalSubject: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadData()
    this.getHignSchool()
    this.fetchCity()
  },
  onShow() {
    const subjectInfo = wx.getStorageSync('subjectInfo')
    this.setData({
      chooseList: wx.getStorageSync('chooseList') || [],
      checkedList: wx.getStorageSync('ids') || [],
      mainSubject: wx.getStorageSync('mainSubject') || '',
      score: wx.getStorageSync('score'),
      ranking: wx.getStorageSync('ranking'),
      disabled: subjectInfo ? true : false,
      currentRegion:wx.getStorageSync('userCitys')
    })
    this.getCitySubject()
  },
  async fetchCity() {
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    this.setData({
      cityList
    })
  },
  async loadData() {
    const {
      result
    } = await fillingInfo()
    const {
      eyeOptions,
      plusOptions
    } = this.data
    if (result) {
      result.isDisability = result.isDisability === 1 ? true : false
      result.isSurgery = result.isSurgery === 1 ? true : false
      result.isColorBlindness = result.isColorBlindness === 1 ? true : false
      result.isColorWeakness = result.isColorBlindness === 1 ? true : false

      this.setData({
        ...result,
        // eyeOptions
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  inputChange(e) {
    const {
      type
    } = e.currentTarget.dataset
    this.setData({
      [type]: e.detail.value
    })
  },
  changeStatus(e) {
    const {
      type,
      value
    } = e.currentTarget.dataset
    this.setData({
      [type]: !value
    })
  },
  changeValue(e) {
    const {
      type,
      value,
      itype,
      index
    } = e.currentTarget.dataset
    if (value == this.data[type]) {
      this.setData({
        [type]: '',
        [itype]: ''
      })
    } else {
      this.setData({
        [type]: value,
        [itype]: index
      })
    }

  },
  switchChange(e) {
    const {
      type
    } = e.currentTarget.dataset
    this.setData({
      [type]: e.detail.value
    })
  },
  async submit(e) {

    const params = e.detail.value
    const {
      isDisability,
      isSurgery,
      id,
      sexIndex, //性别
      roles, //角色
      pluses,
      graphy,
      isColorWeakness,
      isColorBlindness,
      normalSubject, //正常科目
      abnormalSubject, //失常科目
      supernormalSubject, //超常科目
      code
    } = this.data
    params.isDisability = isDisability ? 1 : 0
    params.isSurgery = isSurgery ? 1 : 0
    params.isColorWeakness = isColorWeakness ? 1 : 0
    params.isColorBlindness = isColorBlindness ? 1 : 0
    params.id = id
    params.pluses = pluses
    params.graphy = graphy
    params.roles = roles
    params.sex = sexIndex
    params.cityCode=code
    if (id) {
      const {
        result
      } = await fillingEdit(params)
    } else {
      const {
        result
      } = await fillingAdd(params)
    }
    this.updateScore()
  },
  async getRank() {
    const {
      score,
      currentRegion,
      mainSubject,
      chooseList
    } = this.data
    const ranking = await getApp().getRank(score,
      currentRegion.code,
      '2022',
      mainSubject,
      chooseList)
    this.setData({
      ranking
    })
  },

  async updateScore() {
    const {
      mainSubject,
      chooseList,
      score,
      ranking
    } = this.data
    const secondSelectList = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const secondSelectIds = secondSelectList.map((item) => {
      return item.subjectsId
    })
    const ids = chooseList.map((item) => {
      return item.subjectsId
    })
    const params = {
      score,
      ranking,
      firstSelect: mainSubject,
      secondSelect: secondSelectIds.toString()
    }
    const {
      result
    } = await addScore(params)
    wx.setStorageSync('chooseList', chooseList)
    this.getScore()
  },
  async getScore() {
    var {
      result
    } = await getScore()
    const subjectList = wx.getStorageSync('subjectList') || await getApp().getSubjectList()
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    const currentCityList = cityList.filter((item) => {
      return item.id == result.provinceId
    })
    let newTime = Math.round(new Date())
    const userCitys = {
      code: currentCityList[0].id,
      name: currentCityList[0].title,
      time: newTime
    }
    let checkedIds = []
    const secondSelect = result.secondSelect == '' ? [] : result.secondSelect.split(',')
    var firstSelectSubjects = ''
    var secondSelectSubjects = []
    subjectList.map((item) => {
      if (result.firstSelect !== '' && item.id == result.firstSelect) {
        firstSelectSubjects = item.name
        checkedIds.push(parseInt(result.firstSelect))
      }
      if (secondSelect.indexOf(item.id) > -1 || secondSelect.indexOf(item.id.toString()) > -1) {
        secondSelectSubjects.push(item.name)
        checkedIds.push(parseInt(item.id))
      }
    })
    result.firstSelectSubjects = firstSelectSubjects
    result.secondSelectSubjects = secondSelectSubjects.join(',')
    if (checkedIds.length > 0) {
      wx.setStorageSync('ids', checkedIds)
    }
    wx.setStorageSync('mainSubject', result.firstSelect == '' ? '' : parseInt(result.firstSelect))
    wx.setStorageSync('score', result.score)
    wx.setStorageSync('ranking', result.ranking)
    wx.setStorageSync('year', result.year)
    wx.setStorageSync('userCitys', userCitys)
    wx.setStorageSync('subjectInfo', result)
  },
  /**
   * 生命周期函数--监听页面显示
   */

  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let {
      code
    } = this.data
    const {type}=e.currentTarget.dataset
    const region = e.detail.value
    const provinceLevel = {
      '北京市': '110000',
      '天津市': '120000',
      '重庆市': '500000',
      '上海市': '310000'
    }
    if(type=='region2'){
      provinceLevel[region[0]] ? code = e.detail.code[2] : code = e.detail.code[1]
      this.setData({
        [type]:region,
        code
      })
      this.getHignSchool()
    }
    this.setData({
      [type]:region,
    })
    
  },
  bindPickerChange(e) {
    const {
      subjectList
    } = this.data
    const {
      type,
      itype
    } = e.currentTarget.dataset
    const index = e.detail.value
    this.setData({
      [itype]: index,
      [type]: subjectList[index].name
    })
  },
  // 根据城市获取高中
  async getHignSchool() {
    const {
      code
    } = this.data
    const {
      result
    } = await hignSchool(code)
    this.setData({
      schoolList: result
    })

  },

  async getCitySubject() {
    const code = wx.getStorageSync('userCitys').code
    // console.log('optional/choose--getCitySubject', code)
    const {
      result
    } = await citySubjectList(code)
    //首选科目
    const mainList = result.filter(function (item, index, arr0) {
      return item.isPreferred > 0
    })
    const subjectList = result.filter(function (item, index, arr0) {
      return item.isPreferred == 0
    })
    this.setData({
      list1: mainList
    })
    if (wx.getStorageSync('ids')) {
      const ids = wx.getStorageSync('ids')
      subjectList.map((item) => {
        item['choose'] = ids.indexOf(item.subjectsId) > -1
      })
    } else {
      subjectList.map((item) => {
        item['choose'] = false
      })
    }

    this.setData({
      subList: subjectList,
      length: mainList.length > 0 ? 2 : 3
    })
  },
  chooseMain(e) {
    const {
      list1,
      chooseList,
      checkedList
    } = this.data
    const {
      id,
    } = e.currentTarget.dataset
    const ids = checkedList
    if (ids.indexOf(id) > -1) return
    const deleteIds = list1.filter((item) => {
      return item.subjectsId !== id
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == id
    })
    const subjectsId = deleteIds[0].subjectsId
    chooseList.map((item, index) => {
      if (item.subjectsId == subjectsId) {
        chooseList.splice(index, 1)
      }
    })
    const newList = mainSubjectList.concat(chooseList)
    const newCheckedList = newList.map((item) => {
      return item.subjectsId
    })
    this.setData({
      mainSubject: id,
      chooseList: newList,
      checkedList: newCheckedList,
    })
    // console.log(this.data.chooseList)
  },

  chooseSubject(e) {
    const {
      id,
      choose,
      index,
      name
    } = e.currentTarget.dataset
    var {
      subList, //学科列表
      checkedList, //已选科目id
      chooseList, //已选科目
      length,
      mainSubject,
      list1
    } = this.data
    const hookSubjectList = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == mainSubject
    })
    const hookIds = hookSubjectList.length > 0 ? hookSubjectList.map((item) => {
      return item.subjectsId
    }) : []
    const mainIds = mainSubjectList.length > 0 ? mainSubjectList.map((item) => {
      return item.subjectsId
    }) : []
    subList[index].choose = !choose
    if (choose) {
      //删除
      const index = hookIds.indexOf(id)
      hookIds.splice(index, 1)
      hookSubjectList.splice(index, 1)
    } else {
      if (hookIds.length >= length) {
        subList.map((item) => {
          if (item.subjectsId == hookIds[0]) {
            item.choose = false
          }
        })
        hookIds.splice(0, 1, id)
        hookSubjectList.splice(0, 1, subList[index])

      } else {
        hookIds.push(id)
        hookSubjectList.push(subList[index])
      }
    }
    chooseList = mainSubjectList.concat(hookSubjectList.sort((a,b)=>{return a.id-b.id}))
    checkedList = mainIds.concat(hookIds)
    this.setData({
      subList,
      checkedList,
      chooseList
    })

  },
  changeIndex(e) {
    const {
      list,
      index,
      type,
      checked
    } = e.currentTarget.dataset

    if (checked == undefined) {
      this.setData({
        [type]: index
      })
    } else {
      const array = this.data[list]
      //取消选择
      // array.map((item) => {
      //   item.checked = false
      // })
      array[index].checked = !checked
      this.setData({
        [list]: array
      })
    }

  },
  expand() {
    this.setData({
      expand: !this.data.expand
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})